package com.yang.storage.dao;

import com.yang.springcloud.pojo.Good;
import com.yang.springcloud.pojo.ShoppingCartGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class StorageImp implements StorageDao{
    @Autowired
    DataSource dataSource;

    Connection conn;
    PreparedStatement pstmt;

    @Override
    public Map<String, Object> updateStock(List<ShoppingCartGoods> goodsList) {
        ResultSet rs;
        Good good = new Good();
        int i;
        for(ShoppingCartGoods g:goodsList){
            try {
                conn = dataSource.getConnection();
                pstmt = conn.prepareStatement("SELECT * FROM student where good_id = ?");
                pstmt.setInt(1, g.getGoodId());
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    int id = rs.getInt("good_id");
                    good.setGoodId(id);
                    int stock = rs.getInt("good_stock");
                    good.setGoodStock(stock);
                }

                pstmt = conn.prepareStatement("update student set good_stock=? where good_id=?");
                pstmt.setInt(1, good.getGoodStock()-g.getGoodQuantity());
                pstmt.setInt(2, g.getGoodId());
                i = pstmt.executeUpdate();

                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Map<String, Object> msg = new HashMap<String, Object>();
        msg.put("massage", "更新库存成功");
        msg.put("code", 200);
        return msg;
    }
}
